var _ = {};
(function(window) {
	
	function __addMethod(elms,obj){
		for (var index in elms) {
			var elm = elms[index];	
			for (var key in obj) {
				if (typeof elm[key]=='undefined'){
					elm[key]=obj[key];
				}
			}
		}
	}

	var __methods={
		hasClass: function(cls){
			var el = this[0] || this, flag = -1;
			el = el.getClass();
			for (var i=0; i<=el.length; i++) {
				if(el[i] == cls) flag = i;
				if(flag>0) break;
			}
			return flag;
		},
		getClass: function(){
			var ele = this[0] || this;
			return ele.className ? ele.className.split(' ') : [];
		},
		addClass: function(cls){
			var ele = this[0] || this;
			if(ele.hasClass(cls) == -1) {
				ele.className += " " + cls;
			}

			return ele;
		},
		removeClass: function(cls){
			var ele = this[0] || this, index;
			if (( index = ele.hasClass(cls) ) && index >= 0 ) {
				ele.className = ele.getClass().remove(index).join(' ');
			}
			return ele;
		},
		bind: function(event, fn){
		
			for(var i in this) {
				var el = this[i];
				if(typeof el != 'object') continue;
				
				if(!isIE)	el.addEventListener(event, function(e){ return fn(this, e); }, false);	
				else		el.attachEvent('on'+event, function(e){ 
					return fn(e.srcElement);
				}); // #FIXME: !!! 我只需要div的mouseover 但是 div 里面的所有的内容都加上了这个事件...
			}
			
			return this;
		}
	};
	
	window.$ = function (node){
		if (typeof node == 'string') node = Sizzle(node);
		
		// 修正不支持 Element 的对象
		if(node!=null && !node.test && !window.Element)
			__addMethod(node,__methods);
			
		return node;
	};
	
	if (window.Element) __addMethod([Element.prototype, Array.prototype],__methods);
	
	var tmpls = [];
	
	tmpls["toolbar_tips"] = '<div class="numBg"><p><%=count%></p></div>';
	tmpls["miniloading_dialog"] = '<span style="" ck="clk" id="tips" class="">\
	<div class="dialog_box">\
		<div class="dialog_content">\
			<h1 style="margin-top: -5px;"><%=content%></h1>\
			<%=intro%>\
		</div>\
		<%=confirm%>\
	</div>\
	<div class="pannel_shadow"> </div>\
</span>';
	
	// nav_onlythrow | nav_receive | ico_unread
	/*
	<a ck="del" class="dialogue_del" href="#" title="刪除瓶子及往來對話">\
		<span class="icon ico_dustbin"></span>刪除\
	</a>\
	*/
	tmpls["bottleall_dialog"] = '<div class="bottle_pannel">\
	<div class="bottle_bar pannel_head receivebottleTitle"> <h1> 我的瓶子 </h1> </div>\
	<div class="pannel_content">\
		<div class="nav_con">\
			<div class="nav_<%=nav%>" un="tab">\
				<a class="bottle_tab nav_left" ck="tab" tabid="0"> 撿到的瓶子 </a>\
				<a class="bottle_tab nav_right" ck="tab" tabid="1"> 扔的瓶子 </a>\
			</div>\
		</div>\
		<div class="clr"> </div>\
		<div class="t_mask"> </div>\
		<div class="readContentAll">\
			<% for ( var i = 0; i < datas.length; i++ ) { %>\
			<div iid="<%=datas[i].iid%>" tp="bottle" class="dialogue <% if ( datas[i].session_uid != 0 && datas[i].session_uid != _.uid ) { %>dialogue_unread<%}%> ">\
				<% if ( datas[i].session_uid != 0 && datas[i].session_uid != _.uid ) { %>\
				<span class="icon ico_unread" title="有未回復的回應"></span>\
				<%}else{%><span class="icon ico12_type0"></span><%}%>\
				<img class="avator" src="public/imgs/unknow.gif">\
				<div class="rightpart">\
					<label title="<%=datas[i].created.lefttime()%>" class="graytext"><%=datas[i].created.lefttime()%></label>\
				</div>\
				<p title="<%=datas[i].content%>"><%=datas[i].content%></p>\
			</div>\
			<div class="light_line"> </div>\
			<% } %>\
		</div>\
		<div class="b_mask"> </div>\
	</div>\
</div>\
<div class="pannel_shadow"> </div>';

	tmpls['bottle_session'] = '<div class="bottle_pannel">\
    <a class="ico_close_square" href="javascript:void(0);" ck="rtn">  </a>\
    <div class="bottle_bar pannel_head">\
        <h1> 一個瓶子引起的對話 </h1>\
    </div>\
    <div class="pannel_content">\
	    <div ck="select" class="replyContainer writing" style="height: 140px;">\
			<textarea id="reply_container" class="sendText graytext border" style="height: 70px"></textarea>\
			<span class="charsNotice"> 140字 </span>\
			<a iid="<%=iid%>" ck="send" href="javascript:void(0);" class="btn"> 發送 </a>\
		</div>\
        <div ck="select" class="readContent" writing="true" style="height: 200px;">\
            <div class="readDialogContent">\
            	<% for ( var i = 0; i < datas.length; i++ ) { %>\
            	<div class="dialogue cur_default border <% if ( datas[i].uid == _.uid ) { %>dialogue_picker<%}else{%>dialogue_sender<%}%>">\
            		<div style="width: 173px; height: 0px; overflow: hidden;"></div>\
            		<img class="avator" src="public/imgs/unknow.gif" />\
            		<label class="graytext"><%=datas[i].created.lefttime()%></label>\
            		<p class="b_size wrap photo"><%=datas[i].content%></p>\
            	</div>\
            	<% } %>\
            	<% if ( datas.length <= 1 && send_uid != _.uid ) { %>\
                <div class="type_intro">\
                	<a iid="<%=iid%>" ck="resend" href="javascript:void(0);" class="btn_minor"> 丟回大海 </a>\
                	<a ck="tobtl" href="javascript:void(0);" class="btn_minor"> 回去翻瓶子 </a>\
                </div>\
                <% } %>\
            </div>\
        </div>\
    </div>\
</div>\
<div class="pannel_shadow"></div>';

	tmpls['bottle_send'] = '<div class="bottle_pannel">\
	<div class="pannel_content">\
		<div class="send_top bottle_type0">\
			<span class="ico_type ico_bottle_type0"></span>\
			<p class="type_intro graytext f_size"> 瓶子在海上漂浮，或許會有人撿起並回應您。 </p>\
		</div>\
		<textarea tabindex="2" id="bottle_content" class="sendText " noresize=""></textarea>\
		<div class="send_bottom">\
			<div class="send_bottom_ie6bg"> </div>\
			<div class="bottle_bar send_toolbar">\
				<span class="charsNotice"> 140字 </span>\
				<a ck="send" href="javascript:void(0);" class="btn"> 扔出去 </a>\
				<a ck="cls" href="javascript:void(0);" class="btn_minor"> 關閉 </a>\
			</div>\
		</div>\
	</div>\
</div>\
<div class="pannel_shadow"> </div>';
	
	function checkTextArea(el, e, maxsize, dom) {
		var _o_val = el.value, _val = _o_val.trim();
		if(e.keyCode != 8) el.value = _val.substring(0, maxsize);
		leftsize = maxsize - _val.length - ( e.keyCode == 8 ? -1 : 1 );
		leftsize = leftsize <= 0 ? 0 : ( leftsize > maxsize ? maxsize : leftsize );
		pri.__setHTML(dom, leftsize + '字');
		return leftsize;
	}
	
	var pri = function(){};
	pri.__call = function(method, p, fn){
		p = encodeURIComponent(JSON.stringify(p));
		json_rpc2(_.rpc_host + method + '?json_values=' + p, fn, 'jsonpcb');
	};
	pri.__setHTML = function(dom, html){
		var tmp_doms = $(dom);
		for(var index in tmp_doms) {
			if(
				typeof tmp_doms[index] == 'undefined' || 
				typeof tmp_doms[index].innerHTML == 'undefined'
			) continue;
			tmp_doms[index].innerHTML = html;
		}
		return tmp_doms;
	};
	pri.__show_loading = function(o){
		if(typeof o != 'object') o = {};
		var xhtml = tmpl(tmpls["miniloading_dialog"], {
			"content": typeof o.content == 'undefined' ? '<label id="distance" class="throw_distance">Loading...</label>' : o.content,
			"intro": typeof o.intro == 'undefined' ? '' : o.intro,
			"confirm": typeof o.confirm == 'undefined' ? '' : o.confirm
		});
		var ox = pri.__setHTML( '#bottle_tipsbox', xhtml ).removeClass('hidden');
	};
	pri.__hide_loading = function(){ pri.__setHTML('#bottle_tipsbox', '').addClass('hidden'); };
	
	_.xtmp = 1;
	
	_.feed_store = [
	                { 'caption' :	'想尋找認識到你的另一個他/她，趕快來漂流瓶裡面許個願吧，說不定哪一天你的願望就可以實現。' }
	                ,{ 'caption' :	'想向他/她表白嗎？湊足9999個祝福，也許就可以讓你們的愛更加天長地久！趕快給自己一個可以帶來幸福的漂流瓶吧。' }
	                ,{ 'caption' :	'工作、生活、感情遇到了挫折？來扔個漂流瓶，把自己的快樂和不快樂都藏在裡面。' }
	                ,{ 'caption' :	'想找到你的另一半嗎？趕快來漂流瓶裡面許個願望！放飛自己的漂流瓶，讓願望能夠實現。' }
	                ,{ 'caption' :	'每一個字都是我對你的思念，遠方的你還好嗎？趕快來漂流瓶裡面放個願望，希望遠方的她能夠撿到！' }
	                ,{ 'caption' :	'向他/她告白失敗了，為什麼？也許是你的心不夠誠。趕快給自己一個漂流瓶，希望他/她能看到你的心。' }
	                ,{ 'caption' :	'*uname* 扔出一個漂流瓶，你猜他/她會許什麼願望？想知道他的秘密嗎？趕快把它撈起來瞧一瞧，看一看！' }
	];
	
	_.sendFeed = function() {

		if(fbu_info == false)
			return false;
		
		var capt = (_.feed_store[Math.floor(Math.random() * _.feed_store.length + 1)-1]).caption.replace(/\*uname\*/g, fbu_info.name );

		json_rpc2(graph_url + sitemid + '/feed?link=' + encodeURIComponent('http://apps.facebook.com/city_bottle/') +
				'&name=' + encodeURIComponent('都市漂流瓶') +
				'&picture=' + encodeURIComponent('http://bottle.g.peachcastle.com/lead/public/bottle.jpg') +
				'&caption=' + encodeURIComponent(capt) +
				'&method=post&access_token=' + access_token, function(d) {
		}, 'callback');
	};
	
	_.act_HideTalkGetsession = function(){
		pri.__setHTML('#bottle_interactive', '').addClass('hidden');
		// _.call_BottleGetbottles(_.xtmp);
	};
	_.act_HideBottleSend = function(){
		pri.__setHTML('#bottle_send', '').addClass('hidden');
		// _.call_BottleGetbottles(_.xtmp);
	};
	
	_.act_ShowInvite = function(){ // todo
		
	};

	_.call_BottleSendBefore = function(){
		if(_.ud.wine_cooler <= 0) {
			pri.__show_loading({
				'content':	'您今天已經不能再扔瓶子, 明天再來看看?',
				'intro':		'每天只能有 10 次機會扔瓶子哦~',
				'confirm':	'<div class="dialog_confirm"> <a class="btn" href="javascript:void(0);" ck="invite" > 邀請好友, 獲得更多機會 </a> <a class="btn_minor" href="javascript:void(0);" ck="cls" > 關閉 </a> </div>'
			});
			$('#bottle_tipsbox a[ck=invite]').bind('click', _.act_ShowInvite);
			$('#bottle_tipsbox a[ck=cls]').bind('click', pri.__hide_loading);
			return false;
		}
		_.act_HideTalkGetsession();
		pri.__hide_loading();
		pri.__setHTML('#bottle_send', tmpl( tmpls["bottle_send"], {})).removeClass('hidden');
		
		$('#bottle_send a[ck=send]').bind('click', _.call_BottleSend);
		$('#bottle_send a[ck=cls]').bind('click', _.act_HideBottleSend);
		$('#bottle_send #bottle_content').bind('keydown', function(el, e){
			return !(!checkTextArea(el, e, 140, '#bottle_send .charsNotice'));
		});
	}; // 顯示丟對話框
	_.call_BottleSend = function(){
		var val = $('#bottle_send #bottle_content')[0].value;
		if(val.length<=0) return false;
		
		pri.__show_loading();
		pri.__call('bottle-send', {
			"uid": _.uid,
			"con": val
		}, function(d){
			pri.__hide_loading();
			if(d['code']) {
				_.ud.wine_cooler--;
				_.ud.wine_cooler = _.ud.wine_cooler < 0 ? 0 : _.ud.wine_cooler;
				pri.__setHTML('#toolbar a[act=WineCooler] .numBg p', _.ud.wine_cooler);
				_.act_HideBottleSend();
				pri.__show_loading({
					'content':	'您扔的瓶子漂到了 <label id="distance" class="throw_distance"> ' + parseInt(Math.floor((Math.random() * (3000-15+1))+15)) + ' </label> 公里處',
					'intro':		'<p id="dialog_intro">若有人撿到您的漂流瓶，對方的回應將漂回到您的海灘。</p>',
					'confirm':	'<div class="dialog_confirm"> <a class="btn" href="javascript:void(0);" ck="sendagain" > 再扔一個新瓶子 </a> <a class="btn_minor" href="javascript:void(0);" ck="cls" > 關閉 </a> </div>'
				});
				$('#bottle_tipsbox a[ck=sendagain]').bind('click', _.call_BottleSendBefore);
				$('#bottle_tipsbox a[ck=cls]').bind('click', pri.__hide_loading);
				
				_.sendFeed();
			}
		});
	}; // 丟操作
	
	_.call_BottleFind = function(){
		
		if(_.ud.pick <= 0) {
			pri.__show_loading({
				'content':	'您今天已經不能再撈了, 明天再來看看?',
				'intro':		'每天只能有 10 次機會撈新的瓶子哦~',
				'confirm':	'<div class="dialog_confirm"> <a class="btn" href="javascript:void(0);" ck="invite" > 邀請好友, 獲得更多機會 </a> <a class="btn_minor" href="javascript:void(0);" ck="cls" > 關閉 </a> </div>'
			});
			$('#bottle_tipsbox a[ck=invite]').bind('click', _.act_ShowInvite);
			$('#bottle_tipsbox a[ck=cls]').bind('click', pri.__hide_loading);
			return false;
		}
		
		if(_.ud.pick <= 3 && _.ud.wine_cooler >= 8) {
			pri.__show_loading({
				'content':	'看了這麼多瓶子, 難道你不想扔一個自己的瓶子麼?',
				'intro':		'分享是相互的, 快來分享你的心事吧~<br />必須要扔出去一個瓶子, 你才能撈新的瓶子哦~',
				'confirm':	'<div class="dialog_confirm"> <a class="btn" href="javascript:void(0);" ck="send" > 我也要扔一個瓶子 </a> <a class="btn_minor" href="javascript:void(0);" ck="cls" > 關閉 </a> </div>'
			});
			$('#bottle_tipsbox a[ck=send]').bind('click', _.call_BottleSendBefore);
			$('#bottle_tipsbox a[ck=cls]').bind('click', pri.__hide_loading);
			return false;
		}
		
		pri.__show_loading();
		pri.__call('bottle-find', {
			"uid": _.uid
		}, function(d){
			pri.__hide_loading();
			_.ud.pick--; 
			_.ud.pick = _.ud.pick < 0 ? 0 : _.ud.pick;
			pri.__setHTML('#toolbar a[act=Pick] .numBg p', _.ud.pick);
			if(d['code'] == '0')
				_.call_TalkGetsession(d['iid']);
			else {
				pri.__show_loading({
					'content':	'這是什麼? 也許是一隻螃蟹?',
					'intro':		'真是太幸運了吧~~',
					'confirm':	'<div class="dialog_confirm"> <a class="btn" href="javascript:void(0);" ck="pickagain" > 再撈一次 </a> <a class="btn_minor" href="javascript:void(0);" ck="cls" > 關閉 </a> </div>'
				});
				$('#bottle_tipsbox a[ck=pickagain]').bind('click', _.call_BottleFind);
				$('#bottle_tipsbox a[ck=cls]').bind('click', pri.__hide_loading);
			}
		});
	}; // 撈操作
	
	_.call_BottleResend = function(iid){
		// resend
		pri.__show_loading();
		_.act_HideTalkGetsession();
		
		pri.__call('bottle-resend', {
			"iid": iid
		}, function(d){
			pri.__show_loading({
				'content':	'您扔的瓶子漂到了 <label id="distance" class="throw_distance"> ' + parseInt(Math.floor((Math.random() * (3000-15+1))+15)) + ' </label> 公里處',
				'confirm':	'<div class="dialog_confirm"> <a class="btn_minor" href="javascript:void(0);" ck="cls" > 關閉 </a> </div>'
			});
			$('#bottle_tipsbox a[ck=cls]').bind('click', pri.__hide_loading);
			
			// 刪除自己
			var n = $('div[tp=bottle][iid='+iid+']')[0];
			if( n && n.parentNode )
				n.parentNode.removeChild(n);
		});
	};
	
	_.call_TalkSend = function(iid) {
		var val = $('#bottle_interactive #reply_container')[0].value;
		if(val.length<=0) return false;
		
		pri.__show_loading();
		pri.__call('talk-send', {
			"iid": iid,
			"uid": _.uid,
			"con": val
		}, function(d){
			pri.__hide_loading();
			// @TODO: 提示最終結果
			if(d['code']) {
				_.act_HideTalkGetsession();
			}
		});
	};

	_.call_TalkGetsession	= function(iid){
		_.act_HideBottleSend();
		pri.__show_loading();
		pri.__call('talk-get_session', {
			"iid": iid
		}, function(d){
			pri.__hide_loading();
			pri.__setHTML('#bottle_interactive', tmpl( tmpls["bottle_session"], d)).removeClass('hidden');
			
			$('#bottle_interactive a[ck=tobtl]').bind('click', _.act_HideTalkGetsession);
			$('#bottle_interactive a[ck=rtn]').bind('click', _.act_HideTalkGetsession);
			$('#bottle_interactive a[ck=send]').bind('click', function(el){ _.call_TalkSend(el.getAttribute('iid')); });
			$('#bottle_interactive a[ck=resend]').bind('click', function(el){ _.call_BottleResend(el.getAttribute('iid')); });
			$('#bottle_interactive #reply_container').bind('keydown', function(el, e){
				return !(!checkTextArea(el, e, 140, '#bottle_interactive .charsNotice'));
			});
		});
	};// 看操作
	
	_.call_UserDashboard = function(p, fn){
		pri.__call('user-dashboard', p, function(d){
			_.uid = d.uid;
			_.ud = d;

			// hidden loading...
			$('#loading').addClass('hidden');
			
			// set toolbar count / bind event action 
			d.wine_cooler > 0 && pri.__setHTML('#toolbar a[act=WineCooler]', tmpl( tmpls["toolbar_tips"], {"count": d.wine_cooler}) );
			$('#toolbar a[act=WineCooler]').bind('click', _.call_BottleSendBefore);
			
			d.pick > 0 && pri.__setHTML('#toolbar a[act=Pick]', tmpl( tmpls["toolbar_tips"], {"count": d.pick}) );
			$('#toolbar a[act=Pick]').bind('click', _.call_BottleFind);
			
			// @TODO: bind toolbar action
			$('#toolbar').removeClass('hidden');
			
			typeof fn == 'function' && fn();
		});
	};
	
	_.call_BottleGetbottles = function(is_receive){ // @TODO: 這裡需要加個本地緩存?

		pri.__show_loading();
		
		var p = {};
		p.uid					= _.uid;
		_.xtmp = p.is_receive	= is_receive || 0;
		pri.__call('bottle-get_bottles', p, function(d){
			pri.__hide_loading();

			// show bottle_all dialog
			pri.__setHTML('#bottle_all', tmpl( tmpls["bottleall_dialog"], d)).removeClass('hidden');
			
			$('#bottle_all div[tp=bottle]')
				.bind('mouseover',	function(el){ el.addClass('dialogueOn'); })
				.bind('mouseout',	function(el){ el.removeClass('dialogueOn'); })
				.bind('click',		function(el){ _.call_TalkGetsession(el.getAttribute('iid')); });
			
			var xtmp = ( 1 - p.is_receive == 0 ) ? 0 : 1; 
			$('a[tabid='+xtmp+']').bind('click', function(){ _.call_BottleGetbottles(xtmp); });
			
			if(install && install == '1') {
				pri.__show_loading({
					'content':	'歡迎您第一次來到都市漂流瓶',
					'intro':	'先撈一個瓶子看看吧?',
					'confirm':	'<div class="dialog_confirm"> <a class="btn" href="javascript:void(0);" ck="pick" > 撈一次看看 </a> </div>'
				});
				$('#bottle_tipsbox a[ck=pick]').bind('click', _.call_BottleFind);
			}
		});
	};
	
	_.xx = pri;
})(window);
